<template>
  <el-form
    :model="addGoodsForm"
    :rules="addGoodsRules"
    ref="addGoodsRef"
    label-position="top"
  >
    <!-- v-model绑定activeIndex实现与步骤条联动 -->
    <el-tabs
      :tab-position="'left'"
      v-model="activeName"
      @tab-click="handleClick"
      :before-leave="beforeTabsLeave"
    >
      <el-tab-pane name="0" label="基本信息">
        <el-form-item label="商品分类" prop="goods_cat">
          <el-cascader
          :clearable="true"
            v-model="addGoodsForm.goods_cat"
            :options="categoryList"
            :props="selectedCategory"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="addGoodsForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight" type="number">
          <el-input v-model="addGoodsForm.goods_weight"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number" type="number">
          <el-input v-model="addGoodsForm.goods_number"></el-input>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane name="1" label="商品参数">
        <el-form-item
          v-for="item of categoryManyAttr"
          :key="item.attr_id"
          :label="item.attr_name"
        >
          <el-checkbox-group v-model="item.attr_vals">
            <el-checkbox
              v-for="attr of item.attr_vals"
              :key="attr"
              :label="attr"
              border
              size="mini"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane name="2" label="商品属性">
        <el-form-item
          v-for="item of categoryOnlyAttr"
          :key="item.attr_id"
          :label="item.attr_name"
        >
          <el-input v-model="item.attr_vals"></el-input>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane name="3" label="商品图片">
        <el-form-item>
          <el-upload
            :action="imgUploadURL"
            :on-preview="imgHandlePreview"
            :on-remove="imgHandleRemove"
            :headers="headersObj"
            :on-success="imgUploadSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane name="4" label="商品内容">
        <el-form-item>
          <quill-editor v-model="addGoodsForm.goods_introduce"> </quill-editor>
          <el-button type="primary" class="addbtn" @click="addGoods">
            添加商品
          </el-button>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="图片预览" :visible.sync="imgPreDialogVisible" width="50%">
      <img :src="imgPreviewRUL" alt="" class="img_preview" />
    </el-dialog>
  </el-form>
</template>

<script>
import _ from 'lodash'
export default {
  props: ['activeIndex'],
  data() {
    return {
      activeName: this.activeIndex,
      //添加商品基本信息表单对象
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        //图片上传信息
        pics: [],
        //商品内容介绍信息
        goods_introduce: '',
        //商品的动态属性和静态参数
        attrs: [],
      },
      //添加商品基本信息表单验证
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      //商品分类数据
      categoryList: [],
      //商品类别商品参数数据
      categoryManyAttr: [],
      //商品属性数据
      categoryOnlyAttr: [],
      //级联选择props属性
      selectedCategory: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        //选中任意一项,可以不用父子相连
        checkStrictly: true,
      },
      //选中类别的Id
      selectedCategoryId: [],
      //图片上传地址
      imgUploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      //图片上传请求头信息
      headersObj: {
        Authorization: sessionStorage.getItem('token'),
      },
      //图片预览地址
      imgPreviewRUL: '',
      //控制图片预览弹框的显示/隐藏
      imgPreDialogVisible: false,
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    //获取商品分类数据
    async getCategoryList() {
      let {
        data: { data: res, meta },
      } = await this.$api.getCategoryData()
      if (meta.status === 200) {
        this.categoryList = res
      }
    },
    //级联选择选中触发事件
    handleChange() {
      //默认只可以选中三级分类
      let len = this.addGoodsForm.goods_cat.length
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.selectedCategoryId = []
        this.addGoodsForm.goods_cat = []
        return
      }
    },
    //获取商品数据
    async getGoodsAttr(id, params, attrList, activeName) {
      let {
        data: { data: res, meta },
      } = await this.$api.getGoodsData(id, params)
      if (meta.status === 200) {
        if (activeName === '1') {
          res.forEach((item) => {
            item.attr_vals =
              item.attr_vals.lenght === 0 ? [] : item.attr_vals.split(' ')
          })
          attrList.push(...res)
        } else if (activeName === '2') {
          attrList.push(...res)
        }
      }
    },
    //标签页被选中时
    async handleClick() {
      this.$emit('update:activeIndex', this.activeName)
      if (this.activeName === '1') {
        this.getGoodsAttr(
          this.addGoodsForm.goods_cat[2],
          { params: { sel: 'only' } },
          this.categoryManyAttr,
          this.activeName
        )
      }
      if (this.activeName === '2') {
        this.getGoodsAttr(
          this.addGoodsForm.goods_cat[2],
          {
            params: { sel: 'only' },
          },
          this.categoryOnlyAttr,
          this.activeName
        )
      }
    },
    //判断标签页是否可以切换
    beforeTabsLeave(nextTabs, lastTabs) {
      if (lastTabs === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品类别')
        return false
      }
    },
    //图片预览
    imgHandlePreview(file) {
      console.log(file)
      let {
        response: {
          data: { url },
        },
      } = file
      this.imgPreviewRUL = url
      this.imgPreDialogVisible = true
    },
    //图片移除
    imgHandleRemove(file) {
      console.log(file)
      let {
        response: {
          data: { tmp_path },
        },
      } = file
      this.addGoodsForm.pics = this.addGoodsForm.pics.filter(
        (item) => item.tmp_path !== tmp_path
      )
    },
    //监听图片上传成功
    imgUploadSuccess(response) {
      //临时存储路径
      let picsInfo = {
        tmp_path: response.data.tmp_path,
      }
      this.addGoodsForm.pics.push(picsInfo)
    },
    //点击添加商品按钮,实现添加商品
    addGoods() {
      this.$refs.addGoodsRef.validate(async (valid) => {
        if (!valid) return this.$message.error('添加商品失败')
        //goods_cat,请求要求是字符串
        let goods = _.cloneDeep(this.addGoodsForm)
        goods.goods_cat = goods.goods_cat.join(',')
        //处理动态参数
        this.categoryManyAttr.forEach((item) => {
          let attrInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' '),
          }
          this.addGoodsForm.attrs.push(attrInfo)
          console.log(attrInfo)
        })
        //处理静态参数
        this.categoryOnlyAttr.forEach((item) => {
          let attrInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addGoodsForm.attrs.push(attrInfo)
          console.log(attrInfo)
        })
        goods.attrs = this.addGoodsForm.attrs
        let {
          data: { data, meta },
        } = await this.$api.addGoodsData(goods)
        console.log(data, meta)
        console.log(goods)
        if (meta.status !== 201) return this.$message.error(`${meta.msg}`)
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    },
  },
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.img_preview {
  width: 100%;
}

.addbtn {
  margin-top: 15px;
}
</style>